<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Cookie与Session | 浪飞IT小栈</title>
    <meta name="generator" content="VuePress 1.9.9">
    <link rel="icon" href="/img/favicon.ico">
    <meta name="description" content="前后端技术分享">
    <meta name="keywords" content="前端博客,后端博客,人工智能,个人技术博客,前端,前端开发,前端框架,web前端,前端面试题,技术文档,学习,面试,JavaScript,js,ES6,TypeScript,vue,python,css3,html5,Node,git,github,markdown,java,Spring,Springboot,Redis,mysql">
    <meta name="baidu-site-verification" content="7F55weZDDc">
    <meta name="theme-color" content="#11a8cd">
    
    <link rel="preload" href="/assets/css/0.styles.ada71c49.css" as="style"><link rel="preload" href="/assets/js/app.a2a00aa5.js" as="script"><link rel="preload" href="/assets/js/2.256f807a.js" as="script"><link rel="preload" href="/assets/js/43.08da7ec2.js" as="script"><link rel="prefetch" href="/assets/js/10.ab144fe3.js"><link rel="prefetch" href="/assets/js/11.062e0879.js"><link rel="prefetch" href="/assets/js/12.f9c60882.js"><link rel="prefetch" href="/assets/js/13.0a6ebfcf.js"><link rel="prefetch" href="/assets/js/14.03fc6f12.js"><link rel="prefetch" href="/assets/js/15.19dbf9fd.js"><link rel="prefetch" href="/assets/js/16.6e68160b.js"><link rel="prefetch" href="/assets/js/17.1d678834.js"><link rel="prefetch" href="/assets/js/18.4536fd5c.js"><link rel="prefetch" href="/assets/js/19.9c1b65df.js"><link rel="prefetch" href="/assets/js/20.c5f96e71.js"><link rel="prefetch" href="/assets/js/21.3f0b334e.js"><link rel="prefetch" href="/assets/js/22.55c868be.js"><link rel="prefetch" href="/assets/js/23.91286241.js"><link rel="prefetch" href="/assets/js/24.c1af1909.js"><link rel="prefetch" href="/assets/js/25.a995a755.js"><link rel="prefetch" href="/assets/js/26.abc5dea3.js"><link rel="prefetch" href="/assets/js/27.1eb62850.js"><link rel="prefetch" href="/assets/js/28.b383a871.js"><link rel="prefetch" href="/assets/js/29.088e0d73.js"><link rel="prefetch" href="/assets/js/3.cd716564.js"><link rel="prefetch" href="/assets/js/30.3ccc98d5.js"><link rel="prefetch" href="/assets/js/31.aab7cc23.js"><link rel="prefetch" href="/assets/js/32.5e16b7e6.js"><link rel="prefetch" href="/assets/js/33.4aaeb741.js"><link rel="prefetch" href="/assets/js/34.45e8e898.js"><link rel="prefetch" href="/assets/js/35.5899c97a.js"><link rel="prefetch" href="/assets/js/36.32e2e263.js"><link rel="prefetch" href="/assets/js/37.c4e27bbd.js"><link rel="prefetch" href="/assets/js/38.fe5e60d2.js"><link rel="prefetch" href="/assets/js/39.2cb0b4ee.js"><link rel="prefetch" href="/assets/js/4.edf4d5e7.js"><link rel="prefetch" href="/assets/js/40.08d5bead.js"><link rel="prefetch" href="/assets/js/41.2f80f24b.js"><link rel="prefetch" href="/assets/js/42.43a49913.js"><link rel="prefetch" href="/assets/js/44.7c7cb8a9.js"><link rel="prefetch" href="/assets/js/45.0ddf7e7f.js"><link rel="prefetch" href="/assets/js/46.7c4609a5.js"><link rel="prefetch" href="/assets/js/47.edf3ddf8.js"><link rel="prefetch" href="/assets/js/48.569a90b9.js"><link rel="prefetch" href="/assets/js/49.fa368ac8.js"><link rel="prefetch" href="/assets/js/5.24054156.js"><link rel="prefetch" href="/assets/js/50.b9b3ea7f.js"><link rel="prefetch" href="/assets/js/51.a2ebf0fe.js"><link rel="prefetch" href="/assets/js/52.31f02238.js"><link rel="prefetch" href="/assets/js/53.4110ef1e.js"><link rel="prefetch" href="/assets/js/54.dab741c7.js"><link rel="prefetch" href="/assets/js/55.f27984e9.js"><link rel="prefetch" href="/assets/js/56.bd4c1a8e.js"><link rel="prefetch" href="/assets/js/57.375d40cb.js"><link rel="prefetch" href="/assets/js/58.932e3864.js"><link rel="prefetch" href="/assets/js/59.e657be1b.js"><link rel="prefetch" href="/assets/js/6.b259c061.js"><link rel="prefetch" href="/assets/js/60.88d94274.js"><link rel="prefetch" href="/assets/js/61.fa71d884.js"><link rel="prefetch" href="/assets/js/62.a9d3b3b7.js"><link rel="prefetch" href="/assets/js/63.f849fe75.js"><link rel="prefetch" href="/assets/js/64.1770f7a9.js"><link rel="prefetch" href="/assets/js/65.6afc33db.js"><link rel="prefetch" href="/assets/js/66.799f2eb4.js"><link rel="prefetch" href="/assets/js/67.f36b2f7d.js"><link rel="prefetch" href="/assets/js/68.868cd00b.js"><link rel="prefetch" href="/assets/js/69.4c29b907.js"><link rel="prefetch" href="/assets/js/7.e34ea00f.js"><link rel="prefetch" href="/assets/js/70.1b993ed4.js"><link rel="prefetch" href="/assets/js/71.e16ad4f9.js"><link rel="prefetch" href="/assets/js/72.627505e6.js"><link rel="prefetch" href="/assets/js/73.32768e14.js"><link rel="prefetch" href="/assets/js/74.968a580d.js"><link rel="prefetch" href="/assets/js/75.42d5af3d.js"><link rel="prefetch" href="/assets/js/76.19a69d31.js"><link rel="prefetch" href="/assets/js/77.cf627a78.js"><link rel="prefetch" href="/assets/js/78.07177880.js"><link rel="prefetch" href="/assets/js/8.c4dd00ce.js"><link rel="prefetch" href="/assets/js/9.0ff73be2.js">
    <link rel="stylesheet" href="/assets/css/0.styles.ada71c49.css">
  </head>
  <body class="theme-mode-light">
    <div id="app" data-server-rendered="true"><div class="theme-container sidebar-open have-rightmenu"><header class="navbar blur"><div title="目录" class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><img src="/img/logo.png" alt="浪飞IT小栈" class="logo"> <span class="site-name can-hide">浪飞IT小栈</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/" class="nav-link">首页</a></div><div class="nav-item"><a href="/pages/6138ae/" class="nav-link">Java速通</a></div><div class="nav-item"><a href="/pages/705b35/" class="nav-link">面试经典</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="精品项目" class="dropdown-title"><a href="/project/" class="link-title">精品项目</a> <span class="title" style="display:none;">精品项目</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>桌面端</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/pages/8143cc480faf9a11/" class="nav-link">JavaScript</a></li></ul></li><li class="dropdown-item"><h4>PC后端</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/note/javascript/" class="nav-link">项目1</a></li><li class="dropdown-subitem"><a href="/note/typescript-axios/" class="nav-link">项目二</a></li></ul></li></ul></div></div><div class="nav-item"><a href="/about/" class="nav-link">电子书</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="索引" class="dropdown-title"><a href="/archives/" class="link-title">索引</a> <span class="title" style="display:none;">索引</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/" class="nav-link">分类</a></li><li class="dropdown-item"><!----> <a href="/tags/" class="nav-link">标签</a></li><li class="dropdown-item"><!----> <a href="/archives/" class="nav-link">归档</a></li></ul></div></div><div class="nav-item"><a href="/pages/0c07b2/" class="nav-link">IT杂货铺</a></div><div class="nav-item"><a href="/archives/" class="nav-link">更多资源</a></div> <!----></nav></div></header> <div class="sidebar-mask"></div> <div class="sidebar-hover-trigger"></div> <aside class="sidebar" style="display:none;"><div class="blogger"><img src="https://cdn.jsdelivr.net/gh/langfeiyes/images-khub/avatar.jpg"> <div class="blogger-info"><h3>浪飞yes</h3> <span>无法简单的人儿~</span></div></div> <nav class="nav-links"><div class="nav-item"><a href="/" class="nav-link">首页</a></div><div class="nav-item"><a href="/pages/6138ae/" class="nav-link">Java速通</a></div><div class="nav-item"><a href="/pages/705b35/" class="nav-link">面试经典</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="精品项目" class="dropdown-title"><a href="/project/" class="link-title">精品项目</a> <span class="title" style="display:none;">精品项目</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>桌面端</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/pages/8143cc480faf9a11/" class="nav-link">JavaScript</a></li></ul></li><li class="dropdown-item"><h4>PC后端</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/note/javascript/" class="nav-link">项目1</a></li><li class="dropdown-subitem"><a href="/note/typescript-axios/" class="nav-link">项目二</a></li></ul></li></ul></div></div><div class="nav-item"><a href="/about/" class="nav-link">电子书</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="索引" class="dropdown-title"><a href="/archives/" class="link-title">索引</a> <span class="title" style="display:none;">索引</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/" class="nav-link">分类</a></li><li class="dropdown-item"><!----> <a href="/tags/" class="nav-link">标签</a></li><li class="dropdown-item"><!----> <a href="/archives/" class="nav-link">归档</a></li></ul></div></div><div class="nav-item"><a href="/pages/0c07b2/" class="nav-link">IT杂货铺</a></div><div class="nav-item"><a href="/archives/" class="nav-link">更多资源</a></div> <!----></nav>  <ul class="sidebar-links"><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>开篇</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>基础语法</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>面向对象</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>常用类</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>基础高级</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>数据库</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading open"><span>前端技术</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/pages/84c5d2/" class="sidebar-link">HTML与CSS</a></li><li><a href="/pages/42b6b6/" class="sidebar-link">JavaScript与DOM</a></li><li><a href="/pages/1125b7/" class="sidebar-link">网络编程与Tomcat</a></li><li><a href="/pages/be0e03/" class="sidebar-link">Http与Servlet</a></li><li><a href="/pages/9902e4/" class="sidebar-link">请求与响应</a></li><li><a href="/pages/18345f/" class="sidebar-link">JSP与EL与JSTL</a></li><li><a href="/pages/aa67fd/" class="sidebar-link">WEB版CRUD</a></li><li><a href="/pages/baec2f/" aria-current="page" class="active sidebar-link">Cookie与Session</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header level2"><a href="/pages/baec2f/#一、今日学习内容与目标" class="sidebar-link">一、今日学习内容与目标</a></li><li class="sidebar-sub-header level2"><a href="/pages/baec2f/#二、http-无状态" class="sidebar-link">二、HTTP 无状态</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header level3"><a href="/pages/baec2f/#_2-1-问题说明" class="sidebar-link">2.1 问题说明</a></li><li class="sidebar-sub-header level3"><a href="/pages/baec2f/#_2-2-邮箱案例实现" class="sidebar-link">2.2 邮箱案例实现</a></li></ul></li><li class="sidebar-sub-header level2"><a href="/pages/baec2f/#三、cookie" class="sidebar-link">三、Cookie</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header level3"><a href="/pages/baec2f/#_3-1-cookie-概述" class="sidebar-link">3.1 Cookie 概述</a></li><li class="sidebar-sub-header level3"><a href="/pages/baec2f/#_3-2-cookie-原理图" class="sidebar-link">3.2 Cookie 原理图</a></li><li class="sidebar-sub-header level3"><a href="/pages/baec2f/#_3-3-cookie-基本使用" class="sidebar-link">3.3 Cookie 基本使用</a></li><li class="sidebar-sub-header level4"><a href="/pages/baec2f/#_3-3-1-创建-cookie-对象" class="sidebar-link">3.3.1 创建 Cookie 对象</a></li><li class="sidebar-sub-header level4"><a href="/pages/baec2f/#_3-3-2-响应-cookie-给浏览器" class="sidebar-link">3.3.2 响应 Cookie 给浏览器</a></li><li class="sidebar-sub-header level4"><a href="/pages/baec2f/#_3-3-3-服务器端获取-cookie" class="sidebar-link">3.3.3 服务器端获取 Cookie</a></li><li class="sidebar-sub-header level4"><a href="/pages/baec2f/#_3-3-4-案例代码" class="sidebar-link">3.3.4 案例代码</a></li><li class="sidebar-sub-header level3"><a href="/pages/baec2f/#_3-4-cookie-细节使用" class="sidebar-link">3.4 Cookie 细节使用</a></li><li class="sidebar-sub-header level4"><a href="/pages/baec2f/#_3-4-1-修改-cookie-中的数据" class="sidebar-link">3.4.1 修改 Cookie 中的数据</a></li><li class="sidebar-sub-header level4"><a href="/pages/baec2f/#_3-4-2-设置-cookie-存活时间-掌握" class="sidebar-link">3.4.2 设置 Cookie 存活时间(掌握)</a></li><li class="sidebar-sub-header level4"><a href="/pages/baec2f/#_3-4-3-删除-cookie" class="sidebar-link">3.4.3 删除 Cookie</a></li><li class="sidebar-sub-header level4"><a href="/pages/baec2f/#_3-3-4-cookie-中文问题" class="sidebar-link">3.3.4 Cookie 中文问题</a></li><li class="sidebar-sub-header level3"><a href="/pages/baec2f/#_3-5-cookie-的域和路径-了解" class="sidebar-link">3.5 Cookie 的域和路径（了解）</a></li><li class="sidebar-sub-header level3"><a href="/pages/baec2f/#_3-6-cookie-的小问题" class="sidebar-link">3.6 Cookie 的小问题</a></li></ul></li><li class="sidebar-sub-header level2"><a href="/pages/baec2f/#四、session" class="sidebar-link">四、Session</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header level4"><a href="/pages/baec2f/#_4-1-session-概述" class="sidebar-link">4.1 Session 概述</a></li><li class="sidebar-sub-header level4"><a href="/pages/baec2f/#_4-2-session-的原理图" class="sidebar-link">4.2 Session 的原理图</a></li><li class="sidebar-sub-header level4"><a href="/pages/baec2f/#_4-3-session-的基本使用" class="sidebar-link">4.3 Session 的基本使用</a></li><li class="sidebar-sub-header level5"><a href="/pages/baec2f/#_4-3-1-获取-session-对象" class="sidebar-link">4.3.1 获取 Session 对象</a></li><li class="sidebar-sub-header level5"><a href="/pages/baec2f/#_4-3-2-session-数据共享" class="sidebar-link">4.3.2 Session 数据共享</a></li><li class="sidebar-sub-header level4"><a href="/pages/baec2f/#_4-4-session-的细节使用" class="sidebar-link">4.4 Session 的细节使用</a></li><li class="sidebar-sub-header level5"><a href="/pages/baec2f/#_4-4-1-session-超时管理" class="sidebar-link">4.4.1 Session 超时管理</a></li><li class="sidebar-sub-header level5"><a href="/pages/baec2f/#_4-4-2-url-重写" class="sidebar-link">4.4.2 URL 重写</a></li><li class="sidebar-sub-header level4"><a href="/pages/baec2f/#_4-5-session-使用规范" class="sidebar-link">4.5 Session 使用规范</a></li></ul></li><li class="sidebar-sub-header level2"><a href="/pages/baec2f/#五、小结与作业" class="sidebar-link">五、小结与作业</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header level3"><a href="/pages/baec2f/#_5-1-小结" class="sidebar-link">5.1 小结</a></li><li class="sidebar-sub-header level3"><a href="/pages/baec2f/#_5-2-作业" class="sidebar-link">5.2 作业</a></li></ul></li></ul></li><li><a href="/pages/73e2cb/" class="sidebar-link">文件上传与下载和登录</a></li><li><a href="/pages/f99e33/" class="sidebar-link">项目实战-MIS系统</a></li></ul></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>热门框架</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>前后端分离</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>权限控制</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>NoSQL</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>微服务</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>消息中间件</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>脚手架</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>技术增值</span> <span class="arrow right"></span></p> <!----></section></li></ul> </aside> <div><main class="page"><div class="theme-vdoing-wrapper "><div class="articleInfo-wrap" data-v-06225672><div class="articleInfo" data-v-06225672><ul class="breadcrumbs" data-v-06225672><li data-v-06225672><a href="/" title="首页" class="iconfont icon-home router-link-active" data-v-06225672></a></li> <li data-v-06225672><a href="/categories/?category=Java%E9%80%9F%E9%80%9A" title="分类" data-v-06225672>Java速通</a></li><li data-v-06225672><a href="/categories/?category=%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF" title="分类" data-v-06225672>前端技术</a></li></ul> <div class="info" data-v-06225672><div title="作者" class="author iconfont icon-touxiang" data-v-06225672><a href="https://github.com/langfeiyes" target="_blank" title="作者" class="beLink" data-v-06225672>langfeiyes</a></div> <div title="创建时间" class="date iconfont icon-riqi" data-v-06225672><a href="javascript:;" data-v-06225672>2024-03-03</a></div> <!----></div></div></div> <!----> <div class="content-wrapper"><div class="right-menu-wrapper"><div class="right-menu-margin"><div class="right-menu-title">目录</div> <div class="right-menu-content"></div></div></div> <h1><img src="">Cookie与Session<!----></h1>  <div class="theme-vdoing-content content__default"><h1 id="cookie与session"><a href="#cookie与session" class="header-anchor">#</a> Cookie与Session</h1> <h2 id="一、今日学习内容与目标"><a href="#一、今日学习内容与目标" class="header-anchor">#</a> 一、今日学习内容与目标</h2> <ul><li>理解什么是 HTTP 无状态</li> <li>理解 HTTP 无状态带来的问题</li> <li>掌握会话跟踪的 3 种实现方式</li> <li>理解 Cookie 技术的原理和作用</li> <li>掌握 Cookie 技术的基本使用</li> <li>了解 Cookie 技术的细节操作</li> <li>理解 Session 技术的原理和作用</li> <li>掌握 Session 技术的基本使用</li> <li>了解 Session 技术的细节操作</li></ul> <h2 id="二、http-无状态"><a href="#二、http-无状态" class="header-anchor">#</a> 二、HTTP 无状态</h2> <h3 id="_2-1-问题说明"><a href="#_2-1-问题说明" class="header-anchor">#</a> 2.1 问题说明</h3> <p>HTTP 协议是无状态的，也就是没有记忆力，也无法确定发出请求的用户身份。只负责一问一答。</p> <p><strong>问题</strong>： 一个会话中的多个请求之间无法共享数据。</p> <p>如 : 在操作邮箱的过程中，我们有下面的需求</p> <ol><li>用户访问登录页面，填写账号密码完成登录验证</li> <li>如果验证通过，页面跳转到邮箱首页，显示<strong>当前用户名</strong>。</li> <li>用户点击收件箱，显示<strong>当前用户的邮件列表</strong>，显示登陆的<strong>用户名</strong></li> <li>查看其中一封邮件的内容，显示登陆的<strong>用户名</strong></li></ol> <p><img src="https://cdn.jsdelivr.net/gh/langfeiyes/images-khub/image-20200516232518539.png" alt="image-20200516232518539"></p> <p>②③ 请求的请求对象（req）是各自的，都没有①请求的数据（用户登陆信息），故①②③请求的 req 都是各自的，无法共享数据。而 <strong>实际开发中,我们需要在多个请求之间来共享数据</strong></p> <p><strong>解决方案</strong>： 借助其他方式或技术来实现会话中多个请求间数据的共享</p> <p><strong>传参方式</strong>：直接在路径上带参数（麻烦且数据不安全，不使用）</p> <p><strong>会话跟踪技术</strong>： 推荐</p> <ol><li><p>Cookie 客户端会话跟踪技术</p></li> <li><p>Session 服务端会话跟踪技术(HttpSession)</p></li></ol> <h3 id="_2-2-邮箱案例实现"><a href="#_2-2-邮箱案例实现" class="header-anchor">#</a> 2.2 邮箱案例实现</h3> <ol><li><p>登录页面 	登陆---&gt; 处理登录请求（LoginServlet.java）</p> <div class="language-jsp line-numbers-mode"><pre class="language-text"><code>&lt;h3&gt;用户登录&lt;/h3&gt;
&lt;form action=&quot;/http/login&quot; method=&quot;post&quot;&gt;
    &lt;p&gt;账号：&lt;input type=&quot;text&quot; name=&quot;username&quot;&gt;&lt;/p&gt;
    &lt;p&gt;密码：&lt;input type=&quot;text&quot; name=&quot;password&quot;&gt;&lt;/p&gt;
    &lt;input type=&quot;submit&quot; value=&quot;登录&quot;&gt;
&lt;/form&gt;
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div></li> <li><p>LoginServlet.java  ---&gt; 跳转到首页（index.jsp）</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">protected</span> <span class="token keyword">void</span> <span class="token function">service</span><span class="token punctuation">(</span><span class="token class-name">HttpServletRequest</span> req<span class="token punctuation">,</span> <span class="token class-name">HttpServletResponse</span> resp<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ServletException</span><span class="token punctuation">,</span> <span class="token class-name">IOException</span> <span class="token punctuation">{</span>
    <span class="token comment">// 处理请求编码</span>
    req<span class="token punctuation">.</span><span class="token function">setCharacterEncoding</span><span class="token punctuation">(</span><span class="token string">&quot;UTF-8&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 1 接受请求参数，封装成对象</span>
    <span class="token class-name">String</span> username <span class="token operator">=</span> req<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">&quot;username&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">String</span> password <span class="token operator">=</span> req<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">&quot;password&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 2 调用业务方法来处理请求,模拟和数据中账号信息的匹配</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token string">&quot;admin&quot;</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>username<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> <span class="token string">&quot;1&quot;</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>password<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token comment">// 模拟登录成功，跳转到主页面</span>
        req<span class="token punctuation">.</span><span class="token function">setAttribute</span><span class="token punctuation">(</span><span class="token string">&quot;username&quot;</span><span class="token punctuation">,</span>username<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 3 控制跳转</span>
        req<span class="token punctuation">.</span><span class="token function">getRequestDispatcher</span><span class="token punctuation">(</span><span class="token string">&quot;/WEB-INF/views/index.jsp&quot;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forward</span><span class="token punctuation">(</span>req<span class="token punctuation">,</span>resp<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;登录失败&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br></div></div></li> <li><p>主页（index.jsp）点击查看收件箱 ---&gt;（ListServlet.java）</p> <div class="language-jsp line-numbers-mode"><pre class="language-text"><code>    欢迎: ${username} &lt;br/&gt;
    &lt;a href=&quot;/http/list&quot;&gt;收件箱&lt;/a&gt;
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div></li> <li><p>ListServlet.java  ---&gt; 跳转到邮件列表页（list.jsp）</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">protected</span> <span class="token keyword">void</span> <span class="token function">service</span><span class="token punctuation">(</span><span class="token class-name">HttpServletRequest</span> req<span class="token punctuation">,</span> <span class="token class-name">HttpServletResponse</span> resp<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ServletException</span><span class="token punctuation">,</span> <span class="token class-name">IOException</span> <span class="token punctuation">{</span>
    <span class="token comment">// 1 接受请求参数,封装成对象</span>
    <span class="token class-name">String</span> username <span class="token operator">=</span> req<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">&quot;username&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 2 调用业务方法来处理请求,从数据库中查询邮件列表(模拟)</span>
    <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> list <span class="token operator">=</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span><span class="token string">&quot;邮件1&quot;</span><span class="token punctuation">,</span><span class="token string">&quot;邮件2&quot;</span><span class="token punctuation">,</span><span class="token string">&quot;邮件3&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    req<span class="token punctuation">.</span><span class="token function">setAttribute</span><span class="token punctuation">(</span><span class="token string">&quot;list&quot;</span><span class="token punctuation">,</span>list<span class="token punctuation">)</span><span class="token punctuation">;</span>
    req<span class="token punctuation">.</span><span class="token function">setAttribute</span><span class="token punctuation">(</span><span class="token string">&quot;username&quot;</span><span class="token punctuation">,</span>username<span class="token punctuation">)</span><span class="token punctuation">;</span>
    req<span class="token punctuation">.</span><span class="token function">getRequestDispatcher</span><span class="token punctuation">(</span><span class="token string">&quot;/WEB-INF/views/list.jsp&quot;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forward</span><span class="token punctuation">(</span>req<span class="token punctuation">,</span>resp<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div></li> <li><p>邮件列表页（list.jsp）---&gt; 查看邮件内容（ContentServlet.java）</p> <div class="language-jsp line-numbers-mode"><pre class="language-text"><code>欢迎:${username} &lt;br/&gt;
&lt;c:forEach items=&quot;${list}&quot; var=&quot;email&quot;&gt;
    &lt;a href=&quot;/http/content&quot;&gt;${email}&lt;/a&gt; &lt;br/&gt;
&lt;/c:forEach&gt;
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div></li> <li><p>ContentServlet.java ---&gt; 跳转到邮件内容页（content.jsp）</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">protected</span> <span class="token keyword">void</span> <span class="token function">service</span><span class="token punctuation">(</span><span class="token class-name">HttpServletRequest</span> req<span class="token punctuation">,</span> <span class="token class-name">HttpServletResponse</span> resp<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ServletException</span><span class="token punctuation">,</span> <span class="token class-name">IOException</span> <span class="token punctuation">{</span>
    <span class="token comment">// 1 接受请求参数,封装成对象</span>
    <span class="token class-name">String</span> username <span class="token operator">=</span> req<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">&quot;username&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    req<span class="token punctuation">.</span><span class="token function">setAttribute</span><span class="token punctuation">(</span><span class="token string">&quot;username&quot;</span><span class="token punctuation">,</span>username<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 模拟从数据库中查询到邮件内容</span>
    req<span class="token punctuation">.</span><span class="token function">setAttribute</span><span class="token punctuation">(</span><span class="token string">&quot;content&quot;</span><span class="token punctuation">,</span><span class="token string">&quot;这是邮件内容&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    req<span class="token punctuation">.</span><span class="token function">getRequestDispatcher</span><span class="token punctuation">(</span><span class="token string">&quot;/WEB-INF/views/content.jsp&quot;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forward</span><span class="token punctuation">(</span>req<span class="token punctuation">,</span>resp<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div></li> <li><p>邮件内容页（content.jsp）</p> <div class="language-jsp line-numbers-mode"><pre class="language-text"><code>欢迎: ${username}&lt;br/&gt;
${content}
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div></li></ol> <h2 id="三、cookie"><a href="#三、cookie" class="header-anchor">#</a> 三、Cookie</h2> <h3 id="_3-1-cookie-概述"><a href="#_3-1-cookie-概述" class="header-anchor">#</a> 3.1 Cookie 概述</h3> <p>Cookie是 <strong>客户端技术</strong>，程序把每个用户的数据以 cookie 的形式写给用户各自的浏览器。当用户使用浏览器再次去访问服务器中的 web 资源时，就会带着各自的 cookie 过去服务器。这样, web 资源处理的就是用户各自的数据了。</p> <p><strong>思考</strong>：</p> <ol><li>Cookie 是服务器端创建的还是客户创建的？ 服务器端程序创建</li> <li>Cookie 从哪里带到哪里？服务器端  -&gt; 客户端</li> <li>Cookie 最终存在什么地方？ 浏览器</li> <li>Cookie 什么时候实现数据共享？ 再一次访问服务器端资源时(存入,拿出)</li> <li>Cookie 中数据的传递方向？ 浏览器 -&gt; 服务器 (Cookie)-&gt; 浏览器(存入) -&gt;服务器(获取Cookie数据)</li></ol> <h3 id="_3-2-cookie-原理图"><a href="#_3-2-cookie-原理图" class="header-anchor">#</a> 3.2 Cookie 原理图</h3> <p><img src="https://cdn.jsdelivr.net/gh/langfeiyes/images-khub/image-20200517002505388.png" alt="image-20200517002505388"></p> <h3 id="_3-3-cookie-基本使用"><a href="#_3-3-cookie-基本使用" class="header-anchor">#</a> 3.3 Cookie 基本使用</h3> <p>Cookie 的基本使用无非是</p> <ol><li><p>如何在服务器端创建Cookie？</p></li> <li><p>如何发送 Cookie 给浏览器？</p></li> <li><p>如何获取浏览器带过来的 Cookie？04</p></li></ol> <h4 id="_3-3-1-创建-cookie-对象"><a href="#_3-3-1-创建-cookie-对象" class="header-anchor">#</a> 3.3.1 创建 Cookie 对象</h4> <p>创建对象： Cookie  cookie = new Cookie (String name,String value)</p> <table><thead><tr><th style="text-align:center;">属性</th> <th style="text-align:center;">方法</th> <th style="text-align:center;">描述</th></tr></thead> <tbody><tr><td style="text-align:center;">name</td> <td style="text-align:center;">getName()</td> <td style="text-align:center;">共享数据名称（唯一）</td></tr> <tr><td style="text-align:center;">value</td> <td style="text-align:center;">getValue()</td> <td style="text-align:center;">要共享的数据</td></tr></tbody></table> <h4 id="_3-3-2-响应-cookie-给浏览器"><a href="#_3-3-2-响应-cookie-给浏览器" class="header-anchor">#</a> 3.3.2 响应 Cookie 给浏览器</h4> <p>使用响应对象中的 addCookie (cookie 对象) 将数据响应给浏览器.</p> <blockquote><p>resp.addCookie(cookie)</p></blockquote> <h4 id="_3-3-3-服务器端获取-cookie"><a href="#_3-3-3-服务器端获取-cookie" class="header-anchor">#</a> 3.3.3 服务器端获取 Cookie</h4> <p>浏览器发请求时,自动将 Cookie 发送到服务器,服务器程序直接获取即可。</p> <p>数据在请求中，使用请求对象中的 getCookies() 方法获取所有的 Cookie 对象</p> <blockquote><p>Cookie[] cs = request对象.getCookies();</p></blockquote> <h4 id="_3-3-4-案例代码"><a href="#_3-3-4-案例代码" class="header-anchor">#</a> 3.3.4 案例代码</h4> <ol><li><p>创建 Cookie 响应给浏览器 （LoginServlet）</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">protected</span> <span class="token keyword">void</span> <span class="token function">service</span><span class="token punctuation">(</span><span class="token class-name">HttpServletRequest</span> req<span class="token punctuation">,</span> <span class="token class-name">HttpServletResponse</span> resp<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ServletException</span><span class="token punctuation">,</span> <span class="token class-name">IOException</span> <span class="token punctuation">{</span>
    req<span class="token punctuation">.</span><span class="token function">setCharacterEncoding</span><span class="token punctuation">(</span><span class="token string">&quot;UTF-8&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">String</span> username <span class="token operator">=</span> req<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">&quot;username&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">String</span> password <span class="token operator">=</span> req<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">&quot;password&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token string">&quot;admin&quot;</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>username<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> <span class="token string">&quot;1&quot;</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>password<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token comment">//**** 把数据存入 Cookie 中,写给浏览器 **** </span>
        <span class="token class-name">Cookie</span> cookie <span class="token operator">=</span>  <span class="token keyword">new</span> <span class="token class-name">Cookie</span><span class="token punctuation">(</span><span class="token string">&quot;username&quot;</span><span class="token punctuation">,</span>username<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//**** 把 Cookie 写个浏览器 **** </span>
        resp<span class="token punctuation">.</span><span class="token function">addCookie</span><span class="token punctuation">(</span>cookie<span class="token punctuation">)</span><span class="token punctuation">;</span>
        
        <span class="token comment">// 模拟登录成功，跳转到主页面</span>
        req<span class="token punctuation">.</span><span class="token function">setAttribute</span><span class="token punctuation">(</span><span class="token string">&quot;username&quot;</span><span class="token punctuation">,</span>username<span class="token punctuation">)</span><span class="token punctuation">;</span>
        req<span class="token punctuation">.</span><span class="token function">getRequestDispatcher</span><span class="token punctuation">(</span><span class="token string">&quot;/WEB-INF/views/index.jsp&quot;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forward</span><span class="token punctuation">(</span>req<span class="token punctuation">,</span>resp<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;登录失败&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br></div></div></li> <li><p>从 Cookie 中获取数据（其他 Servlet 或 JSP）</p> <p>Servlet 获取方式</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">// 获取浏览器带过来的 Cookie 数据</span>
<span class="token class-name">Cookie</span><span class="token punctuation">[</span><span class="token punctuation">]</span> cs <span class="token operator">=</span> req<span class="token punctuation">.</span><span class="token function">getCookies</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">for</span><span class="token punctuation">(</span><span class="token class-name">Cookie</span> cookie <span class="token operator">:</span> cs<span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token string">&quot;username&quot;</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>cookie<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
     username <span class="token operator">=</span> cookie<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>JSP 获取方式 cookie 集合中 key 为 username 的 cookie 的 value</p> <div class="language-jsp line-numbers-mode"><pre class="language-text"><code>&lt;%
    String username = null;
    Cookie[] cs = request.getCookies();
    for(Cookie cookie : cs){
        if(&quot;username&quot;.equals(cookie.getName())){
            username = cookie.getValue();
        }
    }
%&gt;    
脚本方式:&lt;%=username%&gt; &lt;br/&gt;
&lt;!-- *** 推荐使用以下方式 *** --&gt;
EL 内置对象方式: ${cookie.username.value}
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div></li></ol> <h3 id="_3-4-cookie-细节使用"><a href="#_3-4-cookie-细节使用" class="header-anchor">#</a> 3.4 Cookie 细节使用</h3> <h4 id="_3-4-1-修改-cookie-中的数据"><a href="#_3-4-1-修改-cookie-中的数据" class="header-anchor">#</a> 3.4.1 修改 Cookie 中的数据</h4> <p>为 Cookie 重新设置数据</p> <ol><li>调用 cookie 对象的 <strong>setValue</strong> 方法来覆盖原本的数据</li> <li>重<strong>新</strong>创建一个同 name 的 <strong>Cookie 对象</strong></li></ol> <p>以上不管使用哪种方式，修改的都是服务器端内存中的 Cookie 数据，和浏览器中存的 Cookie 没有关系，所以需要重新发送新的 Cookie 到浏览器中进行更新。</p> <p><strong>注意： 需要将修改之后的 Cookie 发送到浏览器中进行更新</strong></p> <blockquote><p>resp.addCookie(新的 cookie 对象)</p></blockquote> <h4 id="_3-4-2-设置-cookie-存活时间-掌握"><a href="#_3-4-2-设置-cookie-存活时间-掌握" class="header-anchor">#</a> 3.4.2 设置 Cookie 存活时间(掌握)</h4> <p>默认情况下 Cookie 属于会话 Cookie ，即浏览器关闭则失效，无法使用。</p> <p><img src="https://cdn.jsdelivr.net/gh/langfeiyes/images-khub/image-20200517011232287.png" alt="image-20200517011232287"><br></p> <p>要实现以上功能则需要在创建 Cookie之后给 Cookie 设置存活时间。</p> <p><strong>API</strong>：Cookie 对象的 setMaxAge(int expiry)</p> <table><thead><tr><th style="text-align:center;">expiry数值</th> <th style="text-align:center;">例子</th> <th>含义</th></tr></thead> <tbody><tr><td style="text-align:center;">大于 0 的数值</td> <td style="text-align:center;">setMaxAge(60)</td> <td>Cookie 存活的时间，单位为秒，例：60秒</td></tr> <tr><td style="text-align:center;">0</td> <td style="text-align:center;">setMaxAge(0)</td> <td>立即删除当前 Cookie 对象</td></tr> <tr><td style="text-align:center;">小于 0 的数值</td> <td style="text-align:center;">setMaxAge(-1)</td> <td>会话 Cookie，浏览器关闭则销毁</td></tr></tbody></table> <h4 id="_3-4-3-删除-cookie"><a href="#_3-4-3-删除-cookie" class="header-anchor">#</a> 3.4.3 删除 Cookie</h4> <p>删除 Cookie 只需要使用设置Cookie 存活时间的方法即可，当然需要注意的是一般是中途删除 Cookie ，不是 创建了马上删除，所以在设置删除之后需要重新发送给浏览器去更新删除。</p> <p>API**：</p> <p>Cookie 对象.setMaxAge(0);
response.addCookie(Cookie对象);</p> <h4 id="_3-3-4-cookie-中文问题"><a href="#_3-3-4-cookie-中文问题" class="header-anchor">#</a> 3.3.4 Cookie 中文问题</h4> <p>Cookie 中的 name 属性和 value 都不支持中文,如果有中文,抛以下异常  (Tomcat8.5 以下存在的问题)</p> <p><img src="https://cdn.jsdelivr.net/gh/langfeiyes/images-khub/image-20200517012247240.png" alt="image-20200517012247240"></p> <p>Tomcat8.5 自动处理了 Cookie 中文问题，所以无需手动解决。</p> <p><strong>Tomcat 8.5 以下解决思路</strong>： 将中文进行处理,转换成另一种非中文字符串，获取时转化回来。</p> <p><strong>API</strong></p> <table><thead><tr><th style="text-align:center;">类</th> <th style="text-align:center;">方法</th> <th style="text-align:center;">作用</th></tr></thead> <tbody><tr><td style="text-align:center;">URLEncoder</td> <td style="text-align:center;">encode(“中文”,“UTF-8”)</td> <td style="text-align:center;">把中文字符串转化为非中文</td></tr> <tr><td style="text-align:center;">URLDecoder</td> <td style="text-align:center;">decode（“非中文”，“UTF-8”）</td> <td style="text-align:center;">把非中文转化为中文</td></tr></tbody></table> <blockquote><p>小狼   &lt;===&gt;    %E5%B0%8F%E7%8B%BC</p></blockquote> <p><strong>Cookie 使用</strong>：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">// Cookie 封装数据方式</span>
<span class="token class-name">Cookie</span> cookie <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Cookie</span><span class="token punctuation">(</span><span class="token string">&quot;USER_IN_COOKIE&quot;</span><span class="token punctuation">,</span><span class="token class-name">URLEncoder</span><span class="token punctuation">.</span><span class="token function">encode</span><span class="token punctuation">(</span><span class="token string">&quot;小狼&quot;</span><span class="token punctuation">,</span><span class="token string">&quot;UTF-8&quot;</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// Cookie 获取数据方式</span>
<span class="token class-name">Cookie</span><span class="token punctuation">[</span><span class="token punctuation">]</span> cs <span class="token operator">=</span> request<span class="token punctuation">.</span><span class="token function">getCookies</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Cookie</span> c <span class="token operator">:</span> cs<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token string">&quot;username&quot;</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">URLDecoder</span><span class="token punctuation">.</span><span class="token function">decode</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token string">&quot;UTF-8&quot;</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><h3 id="_3-5-cookie-的域和路径-了解"><a href="#_3-5-cookie-的域和路径-了解" class="header-anchor">#</a> 3.5 Cookie 的域和路径（了解）</h3> <p>为了让浏览器可以设别 Cookie 发送给对应的服务器，以及设别哪些请求需要带 Cookie，默认 Cookie 都带了服务器的设别标识以及需要带 Cookie 的资源标识。</p> <p><strong>设别服务器</strong>： IP:端口,可设别到服务器，但需要两个数据，域名是 IP:端口 整合，所以使用 <strong>域名</strong>，只能是创建Cookie 的服务器的域名。</p> <p><strong>域名分类</strong>：</p> <ul><li>一级（主）域名：baidu.com</li> <li>多级域名：news.<strong>baidu.com</strong></li></ul> <p>想要在相同的主域名下来共享数据，例如，百度和百度地图，百度音乐共用账号，则只需要设置 Cookie 的 domain 即可。主域不同，无法共享数据。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>cookie<span class="token punctuation">.</span><span class="token function">setDomain</span><span class="token punctuation">(</span><span class="token string">&quot;.baidu.com&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><strong>设别资源</strong>： 使用<strong>路径 path</strong>，默认为创建 Cookie的资源所在目录。例：/cookie/login 创建 Cookie，则path为/cookie,则访问 /cookie 打头的资源都会带上该 Cookie。</p> <p>想要在访问服务器上的任意资源都带上 Cookie ，则只需要在创建 Cookie 之后设置下path 为 / 即可。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>cookie<span class="token punctuation">.</span><span class="token function">setPath</span><span class="token punctuation">(</span><span class="token string">&quot;/&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><strong>注意</strong>：</p> <ol><li><p>主域名不同，不管 path 为啥，都无法带上 Cookie</p></li> <li><p><strong>localhost/login 中创建的 Cookie，path 也为 /，则任意资源访问都会带该 Cookie</strong></p></li></ol> <h3 id="_3-6-cookie-的小问题"><a href="#_3-6-cookie-的小问题" class="header-anchor">#</a> 3.6 Cookie 的小问题</h3> <ol><li>如果是一个用户一台电脑,没有问题,但是如果多个人公用一个电脑就存在,不安全</li> <li>使用中文的 (Tomcat8.5 之内) 比较麻烦(编码,解码)</li> <li>一个 Cookie 只能设置一个值,value 是 String 类型</li> <li>一台服务器在一个客户端存储的 Cookie 大小和数量有限
Cookie 大小限制在 4KB 之内；
一台服务器在一个客户端最多保存 20 个 Cookie；
一个浏览器最多可以保存 300 个 Cookie；</li></ol> <h2 id="四、session"><a href="#四、session" class="header-anchor">#</a> 四、Session</h2> <h4 id="_4-1-session-概述"><a href="#_4-1-session-概述" class="header-anchor">#</a> 4.1 Session 概述</h4> <p>Session是<strong>服务器端技术</strong>，利用这个技术，服务器在运行时可以为每一个 <strong>用户的浏览器</strong> 创建一个其<strong>独享的session对象</strong>，由于session为用户浏览器独享，所以用户在访问服务器的 web 资源时，可以把各自的数据放在各自的session中，当用户再去访问服务器中的其它 web 资源时，其它 web 资源再从用户各自的 session 中取出数据为用户服务。</p> <p><strong>思考</strong>：</p> <ol><li>Session 谁来创建？ 服务器</li> <li>Session 存在什么地方？ 服务器</li> <li>Session 什么时候实现数据共享？ 再一次访问服务器端资源时(存入,取出)</li> <li>Session 中数据的传递方向？ 浏览器 -&gt; 服务器(Session)  -&gt; 服务器资源</li> <li>服务器如何设别不同用户的 Session？ 浏览器 -&gt; 服务器(Session)  sessionId -&gt; 浏览器 sessionId -&gt; 服务器</li></ol> <h4 id="_4-2-session-的原理图"><a href="#_4-2-session-的原理图" class="header-anchor">#</a> 4.2 Session 的原理图</h4> <p><img src="https://cdn.jsdelivr.net/gh/langfeiyes/images-khub/image-20200517080220879.png" alt="image-20200517080220879"></p> <p>Session 其底层任然需要依赖Cookie 来传递 Session 的id 值。传递 sessionId 的 Cookie 为会话 Cookie。</p> <p>所以 Session 在浏览器关闭之后就无法使用了。原因是 sessionId 丢失了，服务器会在 30 分钟内清除未有操作的Session 对象。</p> <h4 id="_4-3-session-的基本使用"><a href="#_4-3-session-的基本使用" class="header-anchor">#</a> 4.3 Session 的基本使用</h4> <p>Sessioon 的基本使用无非是如何得到 Session 对象以及如何做数据的共享</p> <h5 id="_4-3-1-获取-session-对象"><a href="#_4-3-1-获取-session-对象" class="header-anchor">#</a> 4.3.1 获取 Session 对象</h5> <p>获取 Session 使用 HttpServletRequest 的 API</p> <table><thead><tr><th>方法</th> <th>作用</th></tr></thead> <tbody><tr><td>getSession(true)</td> <td>判断是否存在 Session ,存在则获取,不存在则创建新 Session 对象返回</td></tr> <tr><td>getSession(false)</td> <td>判断是否存在 Session ,存在则获取,不存在则返回 null （不符合需求）</td></tr> <tr><td>getSession()</td> <td>判断是否存在 Session (浏览器是否带了sessionId),存在则获取,不存在则创建新 Session 对象返回 （推荐）</td></tr></tbody></table> <p>推荐使用 getSession () 满足需求的同时比较简洁</p> <h5 id="_4-3-2-session-数据共享"><a href="#_4-3-2-session-数据共享" class="header-anchor">#</a> 4.3.2 Session 数据共享</h5> <p>HttpSession API</p> <table><thead><tr><th>方法</th> <th>作用</th></tr></thead> <tbody><tr><td>setAttribute(String name, Object value)</td> <td>设置属性名和属性值</td></tr> <tr><td>getAttribute(String name)</td> <td>通过属性名去获取属性值</td></tr> <tr><td>removeAttribute(String name)</td> <td>从Session中移除指定属性名的属性值</td></tr> <tr><td>invalidate()</td> <td>移除整个Session 对象,删除所有的属性和属性值</td></tr></tbody></table> <p>removeAttribute 和 invalidate 视情况选择，一般使用 removeAttribute，避免删除session 对象之后有的数据任然需要使用。</p> <h4 id="_4-4-session-的细节使用"><a href="#_4-4-session-的细节使用" class="header-anchor">#</a> 4.4 Session 的细节使用</h4> <h5 id="_4-4-1-session-超时管理"><a href="#_4-4-1-session-超时管理" class="header-anchor">#</a> 4.4.1 Session 超时管理</h5> <p>设置会话的有效时间，比如金融项目，一般用户登陆状态只保留1~3分钟，不会一直保留。中途离开，回来需要重新登陆。</p> <blockquote><p>session对象.setMaxInactiveInterval(int interval) : 设置session超时时间(秒)(两次请求之间的时间)</p></blockquote> <p>Tomcat 默认是 30 分钟,实际上只保存20来分钟(web.xml)</p> <img src="https://cdn.jsdelivr.net/gh/langfeiyes/images-khub/image-20200517084400842.png" align="left" alt="image-20200517084400842" style="zoom:100%;"> <h5 id="_4-4-2-url-重写"><a href="#_4-4-2-url-重写" class="header-anchor">#</a> 4.4.2 URL 重写</h5> <p>Session 是一个特殊的 Cookie,存在浏览器上,用户可选择不接受 Cookie，此时Session 失效。</p> <p><strong>解决方案</strong>：</p> <ol><li><p>手动在请求url后面拼接jsessionid,使用 <strong>;</strong> 来间隔</p> <p>http://localhost/session/list;jsessionid=6225FDD3988C3B11BD8320899E9B1D2F</p></li> <li><p>自动在请求的URL后面拼接 jsessionid  (自动检测用户是否开启Cookie接收,如果开启了,则不拼接jsessionid)</p> <p>response对象.encodeURL(&quot;/session/content&quot;) ;</p></li></ol> <p><strong>JSP</strong>：</p> <p>脚本获取</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token operator">&lt;</span><span class="token operator">%</span>
    <span class="token class-name">String</span> url <span class="token operator">=</span>  response<span class="token punctuation">.</span><span class="token function">encodeURL</span><span class="token punctuation">(</span><span class="token string">&quot;/session/list&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token operator">%</span><span class="token operator">&gt;</span>
<span class="token operator">&lt;</span>a href<span class="token operator">=</span><span class="token string">&quot;&lt;%=url%&gt;&quot;</span><span class="token operator">&gt;</span>收件箱<span class="token operator">&lt;</span><span class="token operator">/</span>a<span class="token operator">&gt;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p><strong>EL 获取</strong></p> <div class="language-jsp line-numbers-mode"><pre class="language-text"><code>${pageContext.response.encodeURL(&quot;/session/content&quot;)}
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><strong>注意： 一般开发中不去屏蔽Cookie ,一般用户也不会去做</strong></p> <h4 id="_4-5-session-使用规范"><a href="#_4-5-session-使用规范" class="header-anchor">#</a> 4.5 Session 使用规范</h4> <ol><li><p><strong>Session 的属性命名,一般我们命名: XX_IN_SESSION ,而且这个属性名是唯一的</strong> <strong>session.setAttribute(“USER_IN_SESSION”,user);</strong></p></li> <li><p><strong>Session 可以存放多个数据，但是如果数据之间是有联系的，比如username,password 需要封装起来再存入 User(username,password)</strong></p></li> <li><p>服务器在做 session 数据共享时,session 中的对象类型必须实现 java.io.Serializable; 接口(在网络上传递数据). (了解)
序  列  化: 把对象转成二进制
反序列化: 把二进制恢复成对象</p></li></ol> <h2 id="五、小结与作业"><a href="#五、小结与作业" class="header-anchor">#</a> 五、小结与作业</h2> <h3 id="_5-1-小结"><a href="#_5-1-小结" class="header-anchor">#</a> 5.1 小结</h3> <ul><li>理解什么是 HTTP 无状态</li> <li>理解 HTTP 无状态带来的问题</li> <li>掌握会话跟踪的 3 种实现方式</li> <li>理解 Cookie 技术的原理和作用</li> <li>掌握 Cookie 技术的基本使用(写代码)</li> <li>了解 Cookie 技术的细节操作</li> <li>理解 Session 技术的原理和作用</li> <li>掌握 Session 技术的基本使用 (写代码)</li> <li>了解 Session 技术的细节操作</li></ul> <h3 id="_5-2-作业"><a href="#_5-2-作业" class="header-anchor">#</a> 5.2 作业</h3> <ul><li>实现邮箱功能的模拟，演示 HTTP 无状态的效果</li> <li>使用 Cookie 技术来解决 Http 无状态带来的问题</li> <li>使用 Session 技术来解决 Http 无状态带来的问题</li> <li>书写代码练习 Cookie 和 Session  的细节操作（过一下保留印象就可以）</li> <li>拓展：完成购物车的记录（用户没登录的情况，用户登录的情况）</li></ul></div></div>  <div class="page-edit"><!----> <!----> <!----></div> <div class="page-nav-wapper"><div class="page-nav-centre-wrap"><a href="/pages/aa67fd/" class="page-nav-centre page-nav-centre-prev"><div class="tooltip">WEB版CRUD</div></a> <a href="/pages/73e2cb/" class="page-nav-centre page-nav-centre-next"><div class="tooltip">文件上传与下载和登录</div></a></div> <div class="page-nav"><p class="inner"><span class="prev">
        ←
        <a href="/pages/aa67fd/" class="prev">WEB版CRUD</a></span> <span class="next"><a href="/pages/73e2cb/">文件上传与下载和登录</a>→
      </span></p></div></div></div> <div class="article-list"><div class="article-title"><a href="/archives/" class="iconfont icon-bi">最近更新</a></div> <div class="article-wrapper"><dl><dd>01</dd> <dt><a href="/pages/0c07b2/"><div>
            IT杂货铺
            <!----></div></a> <span class="date">03-23</span></dt></dl><dl><dd>02</dd> <dt><a href="/pages/705b35/"><div>
            人事百问
            <!----></div></a> <span class="date">03-22</span></dt></dl><dl><dd>03</dd> <dt><a href="/pages/78eb56/"><div>
            MyBatis-Plus
            <!----></div></a> <span class="date">03-12</span></dt></dl> <dl><dd></dd> <dt><a href="/archives/" class="more">更多文章&gt;</a></dt></dl></div></div></main></div> <div class="footer"><div class="icons"><a href="mailto:langfeiyes@163.com" title="发邮件" target="_blank" class="iconfont icon-youjian"></a><a href="https://github.com/langfeiyes" title="GitHub" target="_blank" class="iconfont icon-github"></a><a href="https://music.163.com/#/playlist?id=755597173" title="听音乐" target="_blank" class="iconfont icon-erji"></a></div> 
  Theme by
  <a href="https://github.com/xugaoyi/vuepress-theme-vdoing" target="_blank" title="本站主题">Vdoing</a> 
    | Copyright © 2024-2024
    <span><a href="https://beian.miit.gov.cn/" target="_blank">粤ICP备18007927号-1</a></span></div> <div class="buttons"><div title="返回顶部" class="button blur go-to-top iconfont icon-fanhuidingbu" style="display:none;"></div> <div title="去评论" class="button blur go-to-comment iconfont icon-pinglun" style="display:none;"></div> <div title="主题模式" class="button blur theme-mode-but iconfont icon-zhuti"><ul class="select-box" style="display:none;"><li class="iconfont icon-zidong">
          跟随系统
        </li><li class="iconfont icon-rijianmoshi">
          浅色模式
        </li><li class="iconfont icon-yejianmoshi">
          深色模式
        </li><li class="iconfont icon-yuedu">
          阅读模式
        </li></ul></div></div> <!----> <!----> <!----></div><div class="global-ui"><div></div></div></div>
    <script src="/assets/js/app.a2a00aa5.js" defer></script><script src="/assets/js/2.256f807a.js" defer></script><script src="/assets/js/43.08da7ec2.js" defer></script>
  </body>
</html>
